package main

import (
	"log"
	"net/http"
	"os"

	"github.com/xi3/qshop/Godeps/_workspace/src/github.com/qor/qor"
	"github.com/xi3/qshop/Godeps/_workspace/src/github.com/qor/qor/admin"

	"github.com/xi3/qshop/Godeps/_workspace/src/github.com/jinzhu/gorm"
	_ "github.com/xi3/qshop/Godeps/_workspace/src/github.com/lib/pq"

	"github.com/xi3/qshop/Godeps/_workspace/src/github.com/gin-gonic/gin"

	"github.com/xi3/qshop/models"
	"github.com/xi3/qshop/resources"
	// "github.com/xi3/qshop/services"
)

var (
	//Db golobal gorm database
	Db gorm.DB

	// Pub   *publish.Publish

	//Admin golobal qor admin
	Admin *admin.Admin
)

func init() {
	var err error
	Db, err = gorm.Open("postgres", os.Getenv("DATABASE_URL"))
	if err != nil {
		panic("Error opening database")
	}
	log.Println("database open sucessfully!")

	Db.AutoMigrate(&models.User{})
	Db.LogMode(true)

	// Pub = publish.New(&Db)
	// Pub.AutoMigrate(&models.User{})

	Admin = admin.New(&qor.Config{DB: &Db})
	resources.Register(Admin)
	// services.Register(Admin, Db)
}

func main() {
	var port string
	port = os.Getenv("PORT")
	if port == "" {
		panic("$PORT must be set")
	}

	mux := http.NewServeMux()
	Admin.MountTo("/admin", mux)

	router := gin.New()
	router.Use(gin.Logger())
	router.LoadHTMLGlob("templates/*.tmpl.html")
	router.Static("/static", "static")

	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl.html", nil)
	})

	mux.Handle("/", router)

	http.ListenAndServe(":"+port, mux)
}
